<template>
  <img ref="img"/>

</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: "authImg",
  props:{
    src:{
      type: String,
      default:''
    }
  },
  data() {
    return {
      currentUrl: null
    }
  },
  watch:{
    src:{
      handler(n){
        if(n){
          this.getImage(n);
        }
      },
      immediate:true
    }
  },
  mounted() {

  },
  methods:{
    getImage(url){
      const currentUrl= window.location.origin;
      // 使用正则表达式截取内容
      const pattern = /\/\/(.*):/;//截取//后面：前面ip
      const result = currentUrl.match(pattern);
      const extractedContent = result ? result[1] : "";
      // const index = currentUrl.indexOf(":");//截取端口号前面的内容
      // const extractedContent2 = currentUrl.substring(0, index);
      // console.log("Extracted Content:", extractedContent,extractedContent2); // 输出截取的内容

      const parsedUrl = new URL(url);
      // 提取路径信息
      const path = parsedUrl.pathname.substr(1);
      let finalUrl=null
      if(extractedContent=='10.10.3.22'){
        finalUrl='http://10.10.3.22:9300/'+path
      }else if(extractedContent=='172.16.250.42'){
        finalUrl='http://172.16.250.42:9300/'+path
      }else {
        finalUrl='http://222.92.79.12:9300/'+path
      }
      let that = this;
      that.$nextTick(()=>{
        let request = new XMLHttpRequest();
        request.responseType = 'blob';
        request.open('get', finalUrl, true);
        // 添加自定义请求头
        request.setRequestHeader('Authorization','Bearer ' + getToken());
        request.setRequestHeader('token','Bearer ' + getToken());
        request.onreadystatechange = e => {
          if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
            that.$refs.img.src = URL.createObjectURL(request.response);
            that.$refs.img.onload = () => {
              that.$refs.img && URL.revokeObjectURL(that.$refs.img.src);
            }
          }
        };
        request.send(null);
      });
    }
  }
}
</script>
<style scoped>

</style>
